"use strict";

require("babel-core/register");
require("../mongodb/db-net.js");
// require('../mysql/db-net.js');

const formidable = require("formidable");
const express = require("express");
const bodyParser = require("body-parser"); //post请求需要引入中间件
var request = require("request"); //服务端请求
const schedule = require("node-schedule"); //定时任务
const cheerio = require("cheerio"); //抓取获取的内容（类似jquery）
const axios = require("axios");

const app = express();

app.use(express.static("dist")); //静态托管

app.get("/testGet", (req, res) => {
  //get接口
  res.status(200);
  const responseData = {
    statusCode: 200,
    body: [{ phone: req.query.phone }, { bb: 2 }],
  };
  res.send(responseData);
});

app.post("/testPost", function (req, res) {
  //post接口

  const form = new formidable.IncomingForm();
  form.parse(req, async (err, fields, files) => {
    if (err) {
      res.send({
        status: 0,
        type: "FORM_DATA_ERROR",
        message: "表单信息错误",
      });
      return;
    }
    const { user_name, password, status = 1 } = fields;
    try {
      if (!user_name) {
        throw new Error("用户名错误");
      } else if (!password) {
        throw new Error("密码错误");
      }
      console.log(user_name);
    } catch (err) {
      console.log(err.message, err);
      res.send({
        status: 0,
        type: "GET_ERROR_PARAM",
        message: err.message,
      });
      return;
    }
    try {
      res.send({
        status: 1,
        message: "注册管理员成功",
      });
    } catch (err) {
      console.log("注册管理员失败", err);
      res.send({
        status: 0,
        type: "REGISTER_ADMIN_FAILED",
        message: "注册管理员失败",
      });
    }
  });
});

const scheduleCronstyle = () => {
  //定时任务
  //每天的凌晨1点1分30秒触发
  schedule.scheduleJob("30 1 1 * * *", () => {
    //定时任务插入你所需要的数据
    const url = `${videoHttp}/`;
    request(url, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        //cheerio 类似于jqyery 用于在服务的操作dom
        var $ = cheerio.load(response.body);
        //把拿到的数据塞入数据库
        addSqlCount(_title, _url, _img);
      }
    });
  });
};
// scheduleCronstyle();

const server = app.listen(8887, (res) => {
  console.log("服务器已启动" + 8887);
});

//请求第三方API
let url =
  "http://apis.juhe.cn/mobile/get?phone=" +
  "13719164517" +
  "&dtype=&key=c35a0335912d66950b92309be39e51aa";
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body); // 请求成功的处理逻辑，注意body是json字符串
  }
});

const superagent = require("superagent");

superagent
  .get("https://www.quword.com/root/search?wd=propellent")
  .end((err, res) => {
    // if (err) console.log(err)
    // console.log(res);
    // const $ = cheerio.load(res.data);
  });

axios //接口参数是json的形式
  .get("https://www.quword.com/root/search?wd=propellent", {})
  .then(function (response) {
    // console.log(response.data);
    const $ = cheerio.load(response.data);
    // console.log($);
    const apple = $(".logo-down");
    // console.log(apple.text()); //fruits__apple
    const listItems = $("p");
    // console.log(listItems.length); // 2
    listItems.each(function (idx, p) {
      // console.log($(p).text());
    });
  })
  .catch(function (error) {
    // 请求失败处理
    console.log(error);
  });

app.get("/Get3", (req, res) => {
  //get接口
  // let url =
  //   "http://apis.juhe.cn/mobile/get?phone=" +
  //   req.query.phone +
  //   "&dtype=&key=c35a0335912d66950b92309be39e51aa";
  // request(url, function (error, response, body) {
  //   if (!error && response.statusCode == 200) {
  //     res.status(200);
  //     console.log(body); // 请求成功的处理逻辑，注意body是json字符串
  //     res.send(JSON.parse(body));
  //   }
  // });
  axios //接口参数是json的形式
    .get(
      "http://apis.juhe.cn/mobile/get?phone=" +
        req.query.phone +
        "&dtype=&key=c35a0335912d66950b92309be39e51aa",
      {}
    )
    .then((response) => res.send(response.data))
    .catch(function (error) {
      // 请求失败处理
      console.log(error);
    });
});
app.post("/Post3", (req, res) => {
  const form = new formidable.IncomingForm();
  form.parse(req, async (err, fields, files) => {
    if (err) {
      res.send({
        status: 0,
        type: "FORM_DATA_ERROR",
        message: "表单信息错误",
      });
      return;
    }
    const { phone, status = 1 } = fields;
    try {
      if (!phone) {
        throw new Error("用户名错误");
      }
      console.log(phone);
      let url =
        "http://apis.juhe.cn/mobile/get?phone=" +
        phone +
        "&dtype=&key=c35a0335912d66950b92309be39e51aa";
      request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          res.status(200);
          console.log(body); // 请求成功的处理逻辑，注意body是json字符串
          res.send(JSON.parse(body));
        }
      });
    } catch (err) {
      console.log(err.message, err);
      res.send({
        status: 0,
        type: "GET_ERROR_PARAM",
        message: err.message,
      });
      return;
    }
  });
});

//mongoose操作数据库

const mongoose = require("mongoose");
const entryData = require("../InitData/entry");
// const { data } = require("cheerio/lib/api/attributes.js");
// import entryData from '../InitData/entry'

const entrySchema = new mongoose.Schema({
  id: Number,
  is_in_serving: Boolean,
  description: String,
  title: String,
  link: String,
  image_url: String,
  icon_url: String,
  title_color: String,
});

const Entry = mongoose.model("Entry", entrySchema);
// console.log(entryData)
Entry.findOne((err, data) => {
  if (!data) {
    for (let i = 0; i < entryData.default.length; i++) {
      Entry.create(entryData.default[i]);
    }
  }
});

Entry.insertMany(entryData.default[0]);

try {
  const entries = Entry.find((err, data) => {
    // console.log(data);
  }, "-_id");
} catch (err) {
  console.log("获取数据失败");
  res.send({
    status: 0,
    type: "ERROR_DATA",
    message: "获取数据失败",
  });
  return;
}

// 定义Schema
const UserSchema = new mongoose.Schema({
  username: {
    // 真实姓名
    type: String,
    required: true,
  },
  password: {
    // 密码
    type: String,
    required: true,
  },
});
// 定义Model
var User = mongoose.model("User", UserSchema);

// 3、定义`user` Entity
var user = new User({
  username: "i5ting",
  password: "0123456789",
});
// 4、对数据库进行操作
// user.save(function (err, doc) {
//   if (err) {
//     console.log("save error:" + err);
//   }
//   console.log("save sucess \n" + doc);
// });

// User.findOne((err, data) => {
//     console.log(data)
// })

// User.find((err, data) => {
//     console.log(data)
// })

const puppeteer = require("puppeteer"); // 引入

async function test() {
  const browser = await puppeteer.launch({
    headless: false, // 本地测试先关掉无头模式
  });
  // 创建一个页面
  const page = await browser.newPage();
  // 设置浏览器视窗
  page.setViewport({
    width: 300,
    height: 600,
  });
  // 输入网页地址
  await page.goto("https://www.quword.com/root/search?wd=propellent", { waitUntil: "domcontentloaded" });
  // 开始截图，全屏截图的关键参数就是这个fullPage，页面会一直滚动到底
  await page.screenshot({ path: "../outputImage.jpg", fullPage: true });
  const result = await page.evaluate(() => {
    let title = document.querySelector('#container');
    console.log(title)

    return {}

});
  // 关闭浏览器
  await browser.close();
}
test();//https://blog.csdn.net/Aays2790/article/details/110736022

